<template>
    <div class="main message-detail">
        <section>
            <el-form :model="formData" :disabled="!isEdit" size="medium" ref="form" label-width="150px">
                <el-form-item label="推送标题:" prop="pushTitle" :rules="commonRules.notNullRule">
                    <el-input v-model="formData.pushTitle" placeholder="推送标题，最多30个字" maxLength="30"></el-input>
                </el-form-item>
                <el-form-item label="标题:" prop="title" :rules="commonRules.notNullRule">
                    <el-input v-model="formData.title" placeholder="标题，最多50个字" maxLength="50"></el-input>
                </el-form-item>
                <el-form-item label="副标题:" prop="subtitle" :rules="commonRules.notNullRule">
                    <el-input v-model="formData.subtitle" placeholder="副标题，最多100个字" maxLength="100"></el-input>
                </el-form-item>
                <el-form-item label="消息封面图:" prop="cover">
                    <el-upload
                            class="avatar-uploader"
                            :action="upladUrl"
                            name="file"
                            :show-file-list="false"
                            :before-upload="beforeUpload"
                            :on-success="uploadSuccess">
                        <img v-if="formData.cover" :src="formData.cover" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="消息类型:" prop="cover">
                    <el-radio :disabled="$route.name === 'messageEdit'" v-model="formData.businessType" :label="1">官方通知</el-radio>
                    <el-radio :disabled="$route.name === 'messageEdit'" v-model="formData.businessType" :label="4">碧选活动</el-radio>
                </el-form-item>
                <el-form-item v-if="formData.businessType===4" label="活动时间:" prop="messageSupporter.endTime" >
                  <el-date-picker
                    style="width: 500px"
                    v-model="formData.useTimeRange"
                    type="datetimerange"
                    range-separator="~"
                    start-placeholder="活动开始时间"
                    end-placeholder="活动结束时间"
                    value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="发送对象:"  :prop="formData.pushTargetLimit==='LIMIT'?'pushTargetList':'pushTargetLimit'" :rules="commonRules.notNullRule">
                    <el-radio :disabled="$route.name === 'messageEdit'"  v-model="formData.pushTargetLimit" label="UNLIMIT" @change="changeValidate">全部</el-radio><br/>
                    <el-radio :disabled="$route.name === 'messageEdit'"  v-model="formData.pushTargetLimit" label="LIMIT" @change="changeValidate">指定</el-radio>
                    <template v-if="formData.pushTargetLimit==='LIMIT'">
                        <div class="push-target-block">
                            <span>用户等级：</span>
                            <el-checkbox-group :disabled="formData.pushTargetList.filter(item => item.targetType ==='BY_MOBILE').length>0" v-model="tempUserLevels" @change="setUserLevels">
                                <el-checkbox label="0" :key="0">普通用户</el-checkbox>
                                <el-checkbox label="1" :key="1">VIP会员</el-checkbox>
                                <el-checkbox label="2" :key="2">钻石会员</el-checkbox>
                                <el-checkbox label="3" :key="3">合伙人</el-checkbox>
                                <!-- <el-checkbox label="1" :key="1">兰蜜</el-checkbox>
                                <el-checkbox label="2" :key="2">大区</el-checkbox>
                                <el-checkbox label="3" :key="3">董事</el-checkbox> -->
                                <!--<el-checkbox label="4" :key="4">大区4</el-checkbox>
                                <el-checkbox label="5" :key="5">董事5</el-checkbox>-->
                            </el-checkbox-group>
                        </div>
                        <div class="push-target-block">
                            <span>指定会员：</span>
                            <div>
                                <el-input :disabled="formData.pushTargetList.filter(item => item.targetType ==='BY_ROLE').length>0" type="textarea" v-model="tempPhones" :rows="3" resize="none" placeholder="请输入用户手机号，多个请用分隔符','隔开，自动过滤非手机号字符串" maxLength="999900" @input="setUserPhones"></el-input>
                                <!--<el-button type="primary" plain>导入手机号</el-button>-->
                            </div>
                            <el-upload
                              class="upload-demo"
                              :disabled="formData.pushTargetList.filter(item => item.targetType ==='BY_ROLE').length>0"
                              ref="upload"
                              :action="excelUpload"
                              name="file"
                              :on-success="uploadExcel"
                              :limit='1'>
                              <el-button :disabled="formData.pushTargetList.filter(item => item.targetType ==='BY_ROLE').length>0"  slot="trigger" size="small" type="primary">导入指定用户</el-button>
                            </el-upload>
                            <!-- <span @click="uploadExcel" style="color: #1da2fd; margin-left: 5px; cursor: pointer;">导入指定用户</span> -->
                        </div>
                    </template>
                </el-form-item>
                <el-form-item label="是否立即发送:" prop="triggerType">
                    <el-radio :disabled="$route.name === 'messageEdit'"  v-model="formData.triggerType" :label="1">是</el-radio>
                    <el-radio :disabled="$route.name === 'messageEdit'"  v-model="formData.triggerType" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="定时发送时间:" v-if="formData.triggerType===2" prop="pushTime" :rules="commonRules.notNullRule">
                    <el-date-picker
                            v-model="formData.pushTime"
                            type="datetime"
                            :picker-options="pickerOptions"
                            placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item v-if="formData.businessType===1" label="消息详情:" prop="content" :rules="commonRules.notNullRule">
                    <tinymce :height="200" v-model="formData.content"></tinymce>
                    <!--<tinymce v-if="formData.businessType===4" :height="200" v-model="formData.content"></tinymce>
                    <el-input type="textarea" v-else v-model="formData.content"></el-input>-->
                </el-form-item>
                <el-form-item v-if="formData.businessType===4" label="活动链接:" prop="messageSupporter.link" :rules="commonRules.ignoreInvite">
                    <el-input type="textarea" v-model="formData.messageSupporter.link"></el-input>
                </el-form-item>

                <el-form-item label="" v-if="isEdit">
                    <el-button type="primary" size="medium" :loading="btnLoading" @click="save">保存</el-button>
                    <el-button type="info" size="medium" plain @click="$router.push({ name: 'messageMsg' })">取消</el-button>
                </el-form-item>
            </el-form>
            <div v-if="!isEdit" style="margin-left: 150px">
                <el-button type="success" size="medium" @click="$router.push({ name: 'messageMsg' })">返回</el-button>
            </div>
        </section>
    </div>
</template>
<script>
  import Tinymce from '@/components/Tinymce'
  import {regexp} from '../../utils/tools'
  export default {
    name: 'messageDetail',
    props: {
      id: {default: ''}
    },
    components: {
      Tinymce
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < (new Date()).getTime() - 8.64e7;
          }
        },
        businessTypeData: ['官方通知', '服务通知', '交易物流', '碧选活动'],
        businessTypeIdData: [],
        businessUrlData: ['system', '', '', 'activity'],

        tempUserLevels: [],
        tempPhones: '',
        pageLoading: false,

        formData: {
          messageId: '',
          pushMessageId: '',
          title: '',
          subtitle: '',
          cover: '',
          businessType: 1,
          businessTypeId: '',
          pushTargetLimit: 'UNLIMIT',
          useTimeRange: [],
          pushTargetList: [],
          triggerType: 1,
          content: '',
          messageSupporter: {}
        },
        btnLoading: false
      }
    },
    computed: {
      isEdit() {
        return this.$route.name !== 'messageMsgView';
      }
    },
    created(){
      this.fetchData();
      this.fetchBusinessTypeIdData();
    },
    methods: {
      uploadExcel(res) {
        this.tempPhones = res.data
        this.setUserPhones(res.data)
      },
      fetchData(){
        if(this.id){
          this.pageLoading = true;
          this.request({
            url: `/mc-manage/messages/${this.id}`,
            method: 'get'
          }).then(({data}) => {
            this.formData = {
              ...data,
              useTimeRange: data.messageSupporter.startTime ? [data.messageSupporter.startTime, data.messageSupporter.endTime]:[]
            };
            this.tempUserLevels = []
            let phoneArray = []
            if (data.pushTargetList){
              data.pushTargetList.map(i => {
                if(i.targetType ==='BY_MOBILE'){
                  phoneArray.push(i.targetValue)
                } else {
                  this.tempUserLevels.push(i.targetValue)
                }
              })
            }
            this.tempPhones = phoneArray.join(',');
            this.pageLoading = false;
          }).catch(err => {
            console.log(err);
            this.pageLoading = false;
          });
        }
      },
      fetchBusinessTypeIdData(){
        this.request({
          url: `/mc-manage/messages/businesstype`,
          method: 'get'
        }).then(({data}) => {
          this.businessTypeIdData = data;
        }).catch(err => {
          console.log(err);
          this.businessTypeIdData = [];
        });
      },
      beforeUpload(file) {
        if (!/image/.test(file.type)) {
          this.$message.error('只能上传图片');
          return false;
        }
        if (file.size > 1024 * 1024) {
          this.$message.error('图片不能大于1M');
          return false;
        }
      },
      uploadSuccess(res) {
        this.formData.cover = this.replaceImgUrl(res.filePath);
      },
      changeValidate(){
        this.$refs.form.clearValidate()
      },
      setUserLevels(value){
        if(!this.formData.pushTargetList){
          this.formData.pushTargetList = []
        }
        let newList = this.formData.pushTargetList.filter(item => item.targetType ==='BY_MOBILE')
        value.map(item => {
          newList.push({
            messageId: this.id,
            targetType: 'BY_ROLE',
            targetValue: item
          })
        });
        if(value && value.length){
          this.tempPhones = ''
        }
        this.formData.pushTargetList = newList;
        this.$refs.form.validateField('pushTargetList')
      },
      setUserPhones(value){
        if(!this.formData.pushTargetList){
          this.formData.pushTargetList = []
        }
        let newList = this.formData.pushTargetList.filter(item => item.targetType ==='BY_ROLE')
        value.split(',').map(item => {
          if(item.match(regexp.phone)){
            newList.push({
              messageId: this.id,
              targetType: 'BY_MOBILE',
              targetValue: item
            })
          }
        });
        if(value && value.split(',').length){
          this.tempUserLevels = []
        }
        this.formData.pushTargetList = newList;
        this.$refs.form.validateField('pushTargetList')
      },
      save(){
        this.$refs.form.validate(valid => {
          if(!valid){
            return;
          }
          if(this.formData.useTimeRange.length){
            this.formData.messageSupporter.startTime = this.formData.useTimeRange[0];
            this.formData.messageSupporter.endTime = this.formData.useTimeRange[1];
          }
          this.btnLoading = true;
          let businessType = this.businessTypeIdData.find(item => parseInt(item.businessType) === this.formData.businessType);
          this.formData.businessTypeId = businessType? businessType.businessTypeId : '';
          this.request({
            url: `/mc-manage/messages/${this.businessUrlData[this.formData.businessType-1]}`,
            method: 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('保存成功');
            this.$router.push({ name: 'messageMsg' })
            this.btnLoading = false;
          }).catch(err => {
            console.log(err);
            this.btnLoading = false;
          });
        })
      }
    }
  }
</script>
<style lang="scss">
    @import "../../styles/_mixin.scss";
    .message-detail{
        .avatar-uploader .el-upload,
        .upload-img-list li,
        .upload-img-list .upload-btn{
            width: 80px;
            height: 80px;
            line-height: 78px;
        }
        .el-form-item{
            max-width: 1100px;
        }
    }

    .push-target-block{
        @include flex;
        margin-left: 24px;
    }
</style>
